package com.yamaikeji.web.controller.demo.controller;

import okhttp3.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Objects;
import java.util.UUID;

public class RongCloudTokenUtil {
    private static final String API_URL = "https://api.cn.ronghub.com/user/getToken.json";

    public static String fetchTokenSync(String userId, String name, String portraitUri, String appKey, String appSecret) throws IOException {
        // 1. 生成签名参数
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonce = UUID.randomUUID().toString();
        String signature = DigestUtils.sha1Hex(appSecret + nonce + timestamp);

        // 2. 构建请求体
        FormBody formBody = new FormBody.Builder()
                .add("userId", userId)
                .add("name", name)
                .add("portraitUri", portraitUri)
                .build();

        // 3. 创建请求
        Request request = new Request.Builder()
                .url(API_URL)
                .addHeader("App-Key", appKey)
                .addHeader("Nonce", nonce)
                .addHeader("Timestamp", timestamp)
                .addHeader("Signature", signature)
                .post(formBody)
                .build();

        // 4. 发送请求
        OkHttpClient client = new OkHttpClient();
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("请求失败: " + response.code());
            }

            // 5. 解析响应
            String json = Objects.requireNonNull(response.body()).string();
            return new JSONObject(json).getString("token");
        } catch (JSONException e) {
            throw new RuntimeException(e);
        }
    }

    public static void fetchTokenAsync(String userId, String name, String portraitUri, String appKey, String appSecret, Callback callback) {
        // 签名生成（同同步版本）
        String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
        String nonce = UUID.randomUUID().toString();
        String signature = DigestUtils.sha1Hex(appSecret + nonce + timestamp);

        // 构建请求
        Request request = new Request.Builder()
                .url(API_URL)
                .post(new FormBody.Builder()
                        .add("userId", userId)
                        .add("name", name)
                        .add("portraitUri", portraitUri)
                        .build())
                .addHeader("App-Key", appKey)
                .addHeader("Nonce", nonce)
                .addHeader("Timestamp", timestamp)
                .addHeader("Signature", signature)
                .build();

        new OkHttpClient().newCall(request).enqueue(callback);
    }

    public static void main(String[] args) {
        // 同步调用
        try {
            String token = fetchTokenSync(
                    "test02",
                    "李四",
                    "https://avatar.example.com/123.jpg",
                    "pvxdm17jph5sr",
                    "3vWAZQqAPJIE5Z"
            );
            System.out.println("获取到的Token: " + token);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}